package cn.itsource.pet.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.itsource.basic.domain.AjaxResult;
import cn.itsource.basic.util.GetUserInfoUtil;
import cn.itsource.basic.util.PageList;
import cn.itsource.org.mapper.ShopMapper;
import cn.itsource.org.mapper.UserMapper;
import cn.itsource.pet.domain.*;
import cn.itsource.pet.mapper.PetDetailMapper;
import cn.itsource.pet.mapper.PetMapper;
import cn.itsource.pet.mapper.PetTypeMapper;
import cn.itsource.pet.service.PetService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.validation.Valid;
import java.util.List;
import java.util.Objects;

@Service
public class PetServiceImpl implements PetService {

    @Autowired
    PetMapper petMapper;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    PetDetailMapper petDetailMapper;
    @Autowired
    PetTypeMapper petTypeMapper;

    @Override
    public PageList pagelist(SearchMasterMessageQuery query) {
        Long shopId = GetUserInfoUtil.getShopId();
        PageList<Pet> pagelist = petMapper.pagelist(query, shopId);
        pagelist.getList().forEach( pet -> {
            pet.setShopName(shopMapper.findByshopId(shopId).getName());
            if(Objects.nonNull(pet.getUserId())) pet.setUserName(userMapper.selectByPrimaryKey(pet.getUserId()).getUsername());
            if(Objects.nonNull(pet.getTypeId())) pet.setPetTypeName(petTypeMapper.selectByPrimaryKey(pet.getTypeId()).getName());
        });
        return pagelist;
    }

    @Override
    public AjaxResult save(PetDTO petDTO) {
        Pet pet = petDTO.getPet();
        PetDetail petDetail = petDTO.getPetDetail();
        Long shopId = GetUserInfoUtil.getShopId();
        pet.setShopId(shopId);
        pet.setState(0l);
        petMapper.insertSelective(pet);

        petDetail.setPetId(pet.getId());
        petDetailMapper.insertSelective(petDetail);
        return AjaxResult.me();
    }

    @Override
    public AjaxResult upbutton(StateIdsDto stateIdsDto) {

        petMapper.upbutton(stateIdsDto);

        return AjaxResult.me();
    }

    @Override
    public AjaxResult deleteBatch(List<Long> ids) {
        petMapper.deleteBatch(ids);
        return AjaxResult.me();
    }

    @Override
    public AjaxResult shenghe(Pet pet) {
        petMapper.updateByPrimaryKey(pet);
        return AjaxResult.me();
    }

    @Override
    public PageList findAll(SearchMasterMessageQuery query) {
        PageHelper.startPage(query.getPage(),query.getPageSize());
        List<Pet> pets = petMapper.selectAll();
        PageInfo<Pet> pageInfo = new PageInfo<>(pets);
        return new PageList(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public Pet findOne(Long id) {
        return petMapper.selectByPrimaryKey(id);
    }
}
